package com.member.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.member.common.utils.StringUtils;
import com.member.shop.domain.SysBizOrder;
import com.member.shop.domain.SysBizTenant;
import com.member.shop.dto.WxPayDto;
import com.member.shop.service.IPayService;
import com.member.shop.service.ISysBizTenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author wangxin
 * @Description
 * @date 2024/12/9 14:56
 **/
@Slf4j
@Service
public class PayServiceImpl implements IPayService {

    @Value("${rm.domain}")
    private String domain;
    @Value("${wx.pay.appId}")
    private String appId;
    @Value("${file.server}")
    private String server;
    @Resource
    private ISysBizTenantService sysBizTenantService;

    @Override
    public Boolean refund(String refundId, SysBizOrder bizOrder) {
        SysBizTenant bizTenant = sysBizTenantService.getById(bizOrder.getTenantId());
        if(bizTenant == null){
            return false;
        }

        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(appId));
        payConfig.setMchId(StringUtils.trimToNull(bizTenant.getWxMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(bizTenant.getWxMchKey()));
//        payConfig.setSubAppId(StringUtils.trimToNull(this.properties.getSubAppId()));
//        payConfig.setSubMchId(StringUtils.trimToNull(this.properties.getSubMchId()));
        payConfig.setKeyPath(StringUtils.trimToNull(server+bizTenant.getWxKeyPath()));

        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);

        int totalFee = bizOrder.getActualPaymentAmount().multiply(BigDecimal.valueOf(100).setScale(0, RoundingMode.HALF_UP)).intValue();
        try {
            WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
            wxPayRefundRequest.setTransactionId(bizOrder.getTransactionId());
            wxPayRefundRequest.setOutRefundNo(refundId);
            wxPayRefundRequest.setTotalFee(totalFee);
            wxPayRefundRequest.setRefundFee(totalFee);
            wxPayRefundRequest.setNotifyUrl(domain + "/mp-api/wx/payment/refundCallback");
            WxPayRefundResult refund = wxPayService.refundV2(wxPayRefundRequest);
            log.info("refund---------->:"+JSONObject.toJSONString(refund));
            return true;
        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 退款 退部分
    @Override
    public Boolean refund2(String refundId, SysBizOrder bizOrder,BigDecimal refundFee) {
        SysBizTenant bizTenant = sysBizTenantService.getById(bizOrder.getTenantId());
        if(bizTenant == null){
            return false;
        }

        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(appId));
        payConfig.setMchId(StringUtils.trimToNull(bizTenant.getWxMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(bizTenant.getWxMchKey()));
//        payConfig.setSubAppId(StringUtils.trimToNull(this.properties.getSubAppId()));
//        payConfig.setSubMchId(StringUtils.trimToNull(this.properties.getSubMchId()));
        payConfig.setKeyPath(StringUtils.trimToNull(server+bizTenant.getWxKeyPath()));

        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);

        int totalFee = bizOrder.getActualPaymentAmount().multiply(BigDecimal.valueOf(100).setScale(0, RoundingMode.HALF_UP)).intValue();
        try {
            WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
            wxPayRefundRequest.setTransactionId(bizOrder.getTransactionId());
            wxPayRefundRequest.setOutRefundNo(refundId);
            wxPayRefundRequest.setTotalFee(totalFee);
            wxPayRefundRequest.setRefundFee(refundFee.multiply(BigDecimal.valueOf(100).setScale(0, RoundingMode.HALF_UP)).intValue());
            wxPayRefundRequest.setNotifyUrl(domain + "/mp-api/wx/payment/refundCallback");
            WxPayRefundResult refund = wxPayService.refundV2(wxPayRefundRequest);
            log.info("refund---------->:"+JSONObject.toJSONString(refund));
            return true;
        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return false;
    }


    @Override
    public WxPayAppOrderResult wxAppPay(WxPayDto wxPayDto) throws WxPayException {
        SysBizTenant bizTenant = sysBizTenantService.getById(wxPayDto.getTenantId());
        if(bizTenant == null){
            throw new WxPayException("未查询到站点配置信息");
        }

        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(appId));
        payConfig.setMchId(StringUtils.trimToNull(bizTenant.getWxMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(bizTenant.getWxMchKey()));
//        payConfig.setSubAppId(StringUtils.trimToNull(this.properties.getSubAppId()));
//        payConfig.setSubMchId(StringUtils.trimToNull(this.properties.getSubMchId()));
        payConfig.setKeyPath(StringUtils.trimToNull(server+bizTenant.getWxKeyPath()));

        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);

        log.info("-------------wxPayDto:"+wxPayDto);
        int totalFee = wxPayDto.getTotalFee().multiply(BigDecimal.valueOf(100).setScale(0, RoundingMode.HALF_UP)).intValue();
        //设置
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();
        wxPayUnifiedOrderRequest.setBody(wxPayDto.getOrderId());
        wxPayUnifiedOrderRequest.setOutTradeNo(wxPayDto.getPayId());
        wxPayUnifiedOrderRequest.setTotalFee(totalFee);
        log.info("支付金额：{}", wxPayUnifiedOrderRequest.getTotalFee());
        wxPayUnifiedOrderRequest.setSpbillCreateIp(wxPayDto.getSpbillCreateIp());
        wxPayUnifiedOrderRequest.setNotifyUrl(domain + wxPayDto.getNotifyUrl());
        wxPayUnifiedOrderRequest.setTradeType("APP");
        wxPayUnifiedOrderRequest.setOpenid(wxPayDto.getOpenId());
        WxPayAppOrderResult order = wxPayService.createOrder(wxPayUnifiedOrderRequest);
        return order;
    }
}
